/**
 *@描述：自定义的文章编辑器，引用了brafr-editor组件库
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import BraftEditor from 'braft-editor';
// @ts-ignore
import {ContentUtils} from 'braft-utils'
import {LinkOutlined,PictureOutlined } from "@ant-design/icons";
import {useState, useEffect} from "react";
import {StaticResourceUploadRequest} from "@/pages/Dashboard/Knowledge/service";
import {InternalLinkModal} from "@/pages/Dashboard/Knowledge/components/InternalLink";
import "./index.less"
import {uniqueId} from "lodash";

const placeholders = [
    {
        id:"1",
        content:'请输入算法/模型简介',
    },
    {
        id:"2",
        content:'请输入项目简介',
    },
    {
        id:"3",
        content:'请从面向领域、应用领域、解决问题方面简单描述本案例',
    },
    {
        id:"4",
        content:'请输入业务流程简介',
    },
    {
        id:"5",
        content:'请输入数据集简介',
    },
    {
        id:"6",
        content:'请输入技术流程简介',
    }
]
const CustomEditor = (
    {
        value,
        onChange,
        type,
    }:{
        value?:any;
        onChange?:(val:any)=>void;
        type?:string;
    }
)=>{

    //todo: 设置组件状态
    const [ showInternalLinkModal ,setShowInternalLinkModal ] = useState(false);
    const [ placeholderItem,setPlaceholderItem ] = useState({
        id:"",
        content:"",
    });

    //组件初始化函数
    //todo: useEffect函数
    useEffect(() => {
        // onChange?.(value??null);
        if(type){
            const content:any = getTypeContent(type);
            // @ts-ignore
            setPlaceholderItem(content);
        }
    }, [type])

    //自定义的插入内部链接触发函数
    //todo: 自定义的插入内部链接触发函数
    const setLink = () => {
        setShowInternalLinkModal(true);
    }

    //创建扩展按钮，查询内部链接按钮
    //todo: 创建扩展按钮，查询内部链接按钮
    const extendControls = [
        {
            key: 'insertLink', // 控件唯一标识，必传
            type: 'button',
            title: '插入内部链接', // 指定鼠标悬停在Control上提示文案
            className: 'insertLink', // 指定按钮的样式名
            html:'插入内部链接',// 指定在按钮中渲染的html字符串
            text: <LinkOutlined />, // 指定按钮文字，此处可传入jsx，若已指定html，则text不会显示
            onClick: () => {
                setLink();
            }
        },
    ]

    //设置编辑器中的按钮列表，里面设置了media按钮的图标和tooltip
    //todo: 设置了media按钮的图标和tooltip
    const controls = [
        'undo', 'redo', 'separator',
        'font-size', 'line-height', 'letter-spacing', 'separator',
        'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
        'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
        'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
        {
            key: 'media', // 使用key来指定控件类型
            title: '上传图片', // 自定义控件title
            text: <PictureOutlined style={{fontSize:20}}/>, // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
        },
        ,'separator','link', 'separator', 'hr', 'separator',
        'clear','fullscreen'
    ];

    //编辑器内容改变时触发函数
    //todo: 编辑器内容改变时触发函数
    const handleChange = (val:any)=> {
        onChange?.(val);
    };

    //设置好插入内部链接后，点击确定按钮是触发
    //todo: onSuccessInsert
    const onSuccessInsert=(item:any)=>{
        setShowInternalLinkModal(false);
        onChange?.(ContentUtils.insertHTML(value,
            '&nbsp;<a href="/knowledge/'+item.id+'" target="_blank">'+item.title+'</a>&nbsp;'
        ));
    }

    //上传触发事件
    //todo: uploadHandler
    const uploadHandler = async (param:any) => {
        const res:AircasKB.ResponseType<string> = await StaticResourceUploadRequest({
            file:param.file
        });
        if(res.code == 200){
            param.progress(100) // 显示完成上传的进度条
            param.success({
                url: res.data,
            })
        }
    }

    // 查看图片发生变化的函数
    const changeImage = async (file:any) => {
        console.log(file)
    }


    //该函数，负责控制不同的知识类型，编辑器默认显示的placeholders内容
    //todo: getTypeContent
    const getTypeContent = (typeId:string):any => {
        let result:any = {};
        for(let i=0;i<placeholders.length;i++){
            if(placeholders[i].id == typeId){
                result={
                    id:placeholders[i].id,
                    content:placeholders[i].content,
                }
                break;
            }
        }
        return result;
    }

    // @ts-ignore
    return (
        <div>
                    <BraftEditor
                        placeholder={placeholderItem.content || "请输入内容"}
                        extendControls={extendControls}
                        controls={controls}
                        value={value}
                        onChange={handleChange}
                        style={{ border: '1px solid #d9d9d9',borderRadius:'5px'}}
                        media={{ uploadFn:uploadHandler, pasteImage: true, onChange: changeImage }}
                    />
                    {showInternalLinkModal && (
                        <InternalLinkModal
                            show={showInternalLinkModal}
                            onSelect={(item: any) => {
                                onSuccessInsert(item);
                            }}
                            onCancel={() => setShowInternalLinkModal(false)}
                        ></InternalLinkModal>
                    )}
        </div>
    )
}

export default CustomEditor;
